package com.boarsoft.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.transaction.IllegalTransactionStateException;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionStatus;

public class SimpleHibernateTxManager implements PlatformTransactionManager {
	protected SessionFactory sessionFactory;

	@Override
	public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
		Session ss = sessionFactory.getCurrentSession();
		Transaction tx = ss.beginTransaction();
		return new DefaultTransactionStatus(tx, true, false, definition.isReadOnly(), false, null);
	}

	@Override
	public void commit(TransactionStatus status) throws TransactionException {
		DefaultTransactionStatus dts = (DefaultTransactionStatus) status;
		Transaction tx = (Transaction) dts.getTransaction();
		if (tx == null) {
			throw new NoTransactionException("Transaction is null");
		}
		if (tx.isActive()) {
			tx.commit();
			return;
		}
		if (status.isCompleted()) {
			throw new IllegalTransactionStateException("Transaction is completed");
		}
	}

	@Override
	public void rollback(TransactionStatus status) throws TransactionException {
		DefaultTransactionStatus dts = (DefaultTransactionStatus) status;
		Transaction tx = (Transaction) dts.getTransaction();
		if (tx == null) {
			throw new NoTransactionException("Transaction is null");
		}
		if (tx.isActive()) {
			tx.rollback();
			return;
		}
		if (status.isCompleted()) {
			throw new IllegalTransactionStateException("Transaction is completed");
		}
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
